package api

import (
	"log"
	"yundata-service/internal"

	"github.com/dgrijalva/jwt-go"
	"gorm.io/gorm"

	am "yundata-service/pkg/model/auth"
)

type NodeAction struct {
	internal.ActionModel
}

func (ac *NodeAction) GetTree() {

	c := ac.Ctx

	currentUser := c.MustGet("user").(jwt.MapClaims)
	db := internal.GDb
	tx := db.Session(&gorm.Session{PrepareStmt: true})
	log.Println(currentUser)

	node := &am.AuthNode{}
	var nodeList []am.AuthNode
	where := "is_menu = 1 and status = 1"
	tx.Model(node).Where(where).Find(&nodeList)

	var nodeTreeList []am.NodeTreeItem
	for _, node := range nodeList {
		nodeTreeItem := am.NodeTreeItem{
			ID:       node.ID,
			ParentID: node.ParentID,
			Title:    node.Title,
			Icon:     node.Icon,
			Path:     node.Path,
			IsMenu:   node.IsMenu,
			Hidden:   node.Hidden,
		}
		nodeTreeList = append(nodeTreeList, nodeTreeItem)
	}

	nodeTree := buildTree(nodeTreeList, 0)
	type Data struct {
		Routes []am.NodeTreeItem `json:"routes"`
	}
	resData := Data{nodeTree}

	ac.Success("获取成功", resData)
}

func buildTree(nodeList []am.NodeTreeItem, pid int) []am.NodeTreeItem {
	var tree []am.NodeTreeItem
	for _, node := range nodeList {
		if node.ParentID == pid {
			children := buildTree(nodeList, node.ID)
			if len(children) > 0 {
				node.Children = children
			}
			tree = append(tree, node)
		}
	}
	return tree
}
